<?php

namespace app\admin\controller\jdy;

use app\common\controller\Backend;
use think\Session;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

use think\Log;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;


use fast\Http;

use app\api\controller\Jdycommon;

/**
 * 工作事项管理
 *
 * @icon fa fa-circle-o
 */
class Task extends Backend
{
    
    /**
     * Task模型对象
     * @var \app\admin\model\jdy\Task
     */
    protected $model = null;
    const ANCHANG_ID = "__taskanchangid__";
    protected $isadmin = false;//

    protected $noNeedRight = ['notifyuser'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jdy\Task;
        $this->view->assign("remindTypeList", $this->model->getRemindTypeList());
        $this->view->assign("taskStatusList", $this->model->getTaskStatusList());
        $this->view->assign("shareToCommList", $this->model->getShareToCommList());
        $this->view->assign("cfzqList", $this->model->getCfzqList());
        $this->view->assign("cfgzfwList", $this->model->getCfgzfwList());

        $group_ids = $this->auth->getGroupIds();
        if (in_array("2", $group_ids) || in_array("1", $group_ids)) {
            $this->isadmin = true;//管理员权限不考虑管辖区域
        }
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $anchang_id = 0;
        $url = $_SERVER['HTTP_REFERER'];
        $anchangname = "";
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchang_id = $urls[$size - 1];
            Session::set(self::ANCHANG_ID, $anchang_id);

            $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        } else {
            Session::set(self::ANCHANG_ID, 0);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($anchang_id > 0) {
                $total = $this->model
                    ->with(['anchang'])
                    ->where($where)
                    ->where('anchang_id', $anchang_id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['anchang'])
                    ->where($where)
                    ->where('anchang_id', $anchang_id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {

                $anchangids = $this->getanchangids();
                $whereA = "";
                if (!$this->isadmin) {
                    if (empty($anchangids)) {
                        $whereA = " anchang_id  = 0 ";
                    } else {
                        $whereA = " anchang_id in (" . $anchangids . ") ";
                    }
                }

                $total = $this->model
                    ->with(['anchang'])
                    ->where($where)
                    ->where($whereA)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['anchang'])
                    ->where($where)
                    ->where($whereA)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            $list = collection($list)->toArray();
            foreach ($list as &$row) {
                $row['maintenanceuser'] = $this->getadminnickname($row['maintenanceuser_id']);
                $row['handleuser'] = $this->getadminnickname($row['handleuser_id']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("anchang_id", $anchang_id);

        return $this->view->fetch();
    }

    function getadminnickname($adminid)
    {
        $admin = \app\admin\model\Admin::get($adminid);
        if ($admin) {
            return $admin->nickname;
        }

        return "";
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['luruman'] = $this->auth->nickname;
                    $result = $this->model->allowField(true)->save($params);

                    //编辑记录,保存记录
                    $trmodel = new \app\admin\model\jdy\Taskrecords;
                    $params['task_id'] = $this->model->id;
                    $trmodel->allowField(true)->save($params);

                    $maintenance = new \app\admin\model\jdy\Maintenance;
//            新增工作事項 [標題: 標題] [提醒日期: 日期] [提醒狀態: 狀態] [內容: 內容]
                    $params['content'] = "新增工作事項[標題: {$this->model->title}][提醒日期: {$this->model->remind_date}][提醒狀態: {$this->model->task_status}][內容: {$this->model->content}]";
                    $maintenance->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $anchang_id = Session::get(self::ANCHANG_ID);
        $this->view->assign("anchang_id", $anchang_id);



        $this->view->assign("acdeviceparams", '{"custom[anchang_id]":"' . $anchang_id . '"}');

        $handleuser_id = 0;
        $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
        $anchangname = "";
        if ($anchang) {
            $handleuser_id = $anchang->companywindow_id;
            $anchangname = $anchang->name;
        }
        $this->view->assign("anchangname", $anchangname);

        $this->view->assign("handleuser_id", $handleuser_id);

        $this->view->assign("maintenanceuser_id", $this->auth->id);
        $this->view->assign("maintenanceuser", $this->auth->nickname);

        //知會人員 案场关联的
        //notifyuser_ids 这个没有意义了
        $Jdycommon = new Jdycommon();
        $list2 = $Jdycommon->getnotifyusers($anchang);
        $notifyuser_ids = "";
        foreach ($list2 as $row) {
            $notifyuser_ids .= $row['id'] . ",";
        }
        $this->view->assign("notifyuser_ids", $notifyuser_ids);

        //指定處理人員
        $list3 = $Jdycommon->gethandleusers($anchang);
        $this->view->assign("handleuserList", $list3);


        return $this->view->fetch();
    }

    public function notifyuser() {
        $list = [];
        $total = 0;

        $anchang_id = Session::get(self::ANCHANG_ID);
        $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);

        $Jdycommon = new Jdycommon();
        $list = $Jdycommon->getnotifyusers($anchang);
        $total = count($list);

        $str = json_encode($_POST);
//        {"searchTable":"tbl","searchKey":"id","searchValue":"16,17","orderBy":[["name","ASC"]],"showField":"name","keyField":"id","keyValue":"16,17","searchField":["name"]}

//        {"q_word":[""],"pageNumber":"1","pageSize":"10","andOr":"AND","orderBy":[["name","ASC"]],"searchTable":"tbl","showField":"name","keyField":"id","searchField":["name"],"name":""}

        Log::record($str, 'ColinAA');
        Log::save();

        $searchValue = "";
        if (isset($_POST['searchValue'])) {
            $searchValue = $_POST['searchValue'];
        }

        $idArr = null;
        if (!empty($searchValue)) {
            $idArr = explode(',', $searchValue);
        }

        $list2 = [];
        //为什么要复制后才行？？？
        //因为 array_unique 转换后 有key索引 "0"
        foreach ($list as $row) {
            $save = false;
            if ($idArr) {
                if (in_array($row['id'], $idArr)) {
                    $save = true;
                }
            } else {
                $save = true;
            }

            if ($save) {
                $list2[] = array(
                    'id' => $row['id'],
                    'name' => $row['name']
                );
            }

        }

//        {"list":{"0":{"id":16,"name":"mirolu"},"1":{"id":17,"name":"蔡錫門"},"2":{"id":18,"name":"李國貞"},"4":{"id":19,"name":"one"},"7":{"id":20,"name":"電池"},"8":{"id":21,"name":"小張"},"9":{"id":22,"name":"賴友任"},"10":{"id":23,"name":"陳韋伶"},"11":{"id":24,"name":"羅伯"},"12":{"id":25,"name":"大仁"},"15":{"id":26,"name":"永鴻"},"17":{"id":27,"name":"恆銓大賴"},"18":{"id":28,"name":"許耿祿"},"19":{"id":29,"name":"章魚燒"}},"list2":[{"id":16,"name":"mirolu"},{"id":17,"name":"蔡錫門"},{"id":18,"name":"李國貞"},{"id":19,"name":"one"},{"id":20,"name":"電池"},{"id":21,"name":"小張"},{"id":22,"name":"賴友任"},{"id":23,"name":"陳韋伶"},{"id":24,"name":"羅伯"},{"id":25,"name":"大仁"},{"id":26,"name":"永鴻"},{"id":27,"name":"恆銓大賴"},{"id":28,"name":"許耿祿"},{"id":29,"name":"章魚燒"}],"total":14}

        return json(['list' => $list2, 'total' => $total]);
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['luruman'] = $this->auth->nickname;
                    $result = $row->allowField(true)->save($params);

                    //编辑记录,保存记录
                    $trmodel = new \app\admin\model\jdy\Taskrecords;
                    $params['task_id'] = $row->id;
                    $trmodel->allowField(true)->save($params);

                    $maintenance = new \app\admin\model\jdy\Maintenance;
                    //修改工作事項[標題: 標題] [提醒日期: 日期] [提醒狀態: 狀態] [內容: 內容]
//                    $params['content'] = "修改工作事項[標題: {$row->title}][提醒日期: {$row->remind_date}][提醒狀態: {$row->task_status}][內容: {$row->content}]";
                    $params['content'] = $params['content1'];
                    $maintenance->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $anchang = \app\admin\model\jdy\Anchang::get($row->anchang_id);
        $anchangname = "";
        if ($anchang) {
            $anchangname = $anchang->name;
        }

        $this->view->assign("row", $row);
        $this->view->assign("acdeviceparams", '{"custom[anchang_id]":"' . $row->anchang_id . '"}');
        $this->view->assign("anchangname", $anchangname);

        $this->view->assign("maintenanceuser_id", $this->auth->id);
        $this->view->assign("maintenanceuser", $this->auth->nickname);
        $this->view->assign("content0", $this->getcontent0($row->anchang_id, $row->id));

        $Jdycommon = new Jdycommon();
        $list2 = $Jdycommon->getnotifyusers($anchang);
        $notifyusers = "";
        foreach ($list2 as $row) {
            $notifyusers .= $row['name'] . ",";
        }
        $this->view->assign("notifyusers", $notifyusers);

        //指定處理人員
        $list3 = $Jdycommon->gethandleusers($anchang);
        $this->view->assign("handleuserList", $list3);

        $this->view->assign("content1", date("Y-m-d") . " " . $this->auth->nickname . " ");

        return $this->view->fetch();
    }

    function getcontent0($anchang_id, $task_id)
    {
        $content0 = "";
        $list = \app\admin\model\jdy\Maintenance::where('anchang_id', $anchang_id)
            ->where('task_id', $task_id)
            ->field('content, message, switch, create_time, luruman')
            ->order("create_time desc")
            ->select();

        foreach ($list as $row) {
            $message = "";
            if ($row->message) {
                $message = $row->message;
            }

            $content0 .= $row->create_time . "\n录入人員:" .$row->luruman. "\n内容:" . $row->content . "\n主管留言:" . $message . "\n\n";
        }

        return $content0;
    }

    public function getanchanglist()
    {
        $anchangidlist = json_decode($this->auth->anchangids, TRUE);
        $xianshi = [];
        $xianshi[] = $this->auth->xianshi1;
        $xianshi[] = $this->auth->xianshi2;
        $xianshi[] = $this->auth->xianshi3;
        $xianshi[] = $this->auth->xianshi4;
        $xianshi[] = $this->auth->xianshi5;

        $xzq = [];
        $xzq[] = $this->auth->xzq1;
        $xzq[] = $this->auth->xzq2;
        $xzq[] = $this->auth->xzq3;
        $xzq[] = $this->auth->xzq4;
        $xzq[] = $this->auth->xzq5;

        $xianshis = "";//只有市
        $xianshisA = "";
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xianshi[$i]) && empty($xzq[$i])) {
                if (empty($xianshis)) {
                    $xianshis = $xianshi[$i];
                    $xianshisA = "'" . $xianshis . "'";
                } else if (strpos($xianshis, $xianshi[$i]) === false) {
                    $xianshis .= ',' . $xianshi[$i];
                    $xianshisA .= ",'" . $xianshi[$i] . "'";
                }
            }
        }

        $xzqs = "";//
        $xzqsA = "";//
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xzq[$i]) && !empty($xianshi[$i]) && strpos($xianshis, $xianshi[$i]) === false) {
                if (empty($xzqs)) {
                    $xzqs = $xzq[$i];
                    $xzqsA = "'" . $xzqs . "'";
                } else if (strpos($xzqs, $xzq[$i]) === false) {
                    $xzqs .= ',' . $xzq[$i];
                    $xzqsA .= ",'" . $xzq[$i] . "'";
                }
            }
        }

        $whereA = "";
        if (!empty($xianshis)) {
            $whereA = " xianshi in (" . $xianshisA . ") ";
        }

        if (!empty($xzqs)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " xzq in (" . $xzqsA . ") ";
        }

        $anchangids = "";//"117,116"
        if ($anchangidlist) {
            foreach ($anchangidlist as $row) {
                if (empty($anchangids)) {
                    $anchangids = $row['id'];
                } else {
                    $anchangids .= ',' . $row['id'];
                }
            }
        }

        if (!empty($anchangids)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " id in (" . $anchangids . ") ";
        }

        $list = [];
        if (!empty($whereA)) {
            $list = \app\admin\model\jdy\Anchang::where($whereA)->select();
        }

        return $list;
    }

    public function getanchangids() {
        $anchangidlist = $this->getanchanglist();
        $anchangids = "";
        foreach ($anchangidlist as $row) {
            if (empty($anchangids)) {
                $anchangids = $row['id'];
            } else {
                $anchangids .= ',' . $row['id'];
            }
        }
        return $anchangids;
    }

}
